#pragma once
#include "Reactor.hpp"
#include <string>
#include <cstring>
#include <cstdlib>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include "Service.hpp"
#include "Util.hpp"
int Accepter(Event *evp)
{
    std::cout << "有新的链接到来..." << evp->sock << "读就绪事件发生了..." << std::endl;
    int listen_sock = evp->sock;

    //由于listen_sock是非阻塞的套接字，所以我们要循环读取
    while (true)
    {
        struct sockaddr_in peer;
        socklen_t len = sizeof(peer);
        int sock = accept(listen_sock, (struct sockaddr *)&peer, &len);
        if (sock < 0)
        {
            std::cout << "accept new link done\n";
            break;
        }
        std::cout << "Accepter successfully " << sock << std::endl;
        SetNoBlock(sock);
        //获取新连接成功,那么就构建事件的节点Event,形成柴火加入到反应堆中
        Event *new_evp = new Event;
        new_evp->sock = sock;
        new_evp->R = evp->R; //为什么要让所有的Event回指到反应堆呢？1.通过Event事件就直接调用Reactor中的InsertEvent方法
        // Recver Sender Errorer 是真正的IO处理函数，只负责读取
        new_evp->RegisterCallBack(Recver, Sender, Errorer); //给通信文件描述符sock注册回调函数

        //柴火加入反应堆
        evp->R->InsertEvent(new_evp, EPOLLIN | EPOLLET);
    }
}
